package com.ktjy.ktmall.servlet;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.ktjy.ktmall.entity.*;
import com.ktjy.ktmall.service.CartItemService;
import com.ktjy.ktmall.service.impl.CartItemServiceImpl;
import com.ktjy.ktmall.entity.vo.CartItemVo;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@WebServlet(name = "CartServlet", urlPatterns = "/uni/member/cart")
public class CartServlet extends HttpServlet {
    private CartItemService cartService = null;
    @Override
    public void init(ServletConfig config) throws ServletException {
        cartService = new CartItemServiceImpl();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1、创建out对象
        PrintWriter out = response.getWriter();
        // 2、获取从小程序端请求过来的参数
        String params = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
        // 3、将请求参数字符串转换成JSONObject对象，之后从JSONObject对象中取出值
        JSONObject entries = JSONUtil.parseObj(params);
        String opr = entries.get("opr", String.class);
        AjaxResult result = null;
        if ("addCart".equals(opr)) {
            // 加入购物车
            CartItem cart = entries.get("cart", CartItem.class);
            int i = cartService.insert(cart);
            if (i > 0) {
                result = AjaxResult.success("购物车成功!");
            } else {
                result = AjaxResult.error("添加失败!");
            }
        } else if ("findCartGoodsList".equals(opr)) {
            Integer userId = entries.get("userId", Integer.class);
            List<CartItem> list = cartService.findByUserId(userId);
            List<CartItemVo> vo = new ArrayList<>();
            // 将List<CartItem> list集合的数据转换成List<CartItemVo> vo集合的数据，再响应到小程序端。
            if (list != null && list.size() > 0) {
                for (CartItem c: list) {
                    SkuItem sku = c.getSkuItem();

                    GoodsItem goods = sku.getGoods();
                    StringBuffer attrsText = new StringBuffer("");
                    // 使用for循环取出商品sku的规格属性值，多个属性值使用空格隔开。
                    for (AttrItem spec : sku.getSpecs()) {
                        for (AttrValues value : spec.getValues()) {
                            attrsText.append(value.getName() + " ");
                        }
                    }
                    CartItemVo cart = new CartItemVo(c.getId(), goods.getId(), sku.getId(), goods.getGoodsName(),sku.getPicture(),c.getGoodsCount(),sku.getPrice(),(int)sku.getInventory(),c.getSelected() == 1 ? true : false,attrsText.toString().trim());
                    cart.setNowPrice(new BigDecimal("0.9").multiply(cart.getPrice()).setScale(2));
                    vo.add(cart);
                }
            }
            result = AjaxResult.success("商品列表获取成功!", vo);
        } else if ("delCart".equals(opr)) {
            // 支持批量删除购物车列表信息
            // 接收从小程序传递过来的购物车ids
            Integer [] ids = entries.get("ids", Integer[].class);
            // 使用Arrays将Integer[] ids数组转换成以逗号连接的字符串
            try {
                cartService.batchDel(Arrays.stream(ids).map(Object::toString).collect(Collectors.joining(",")));
                result = AjaxResult.success("删除成功!");
            } catch (Exception e) {
                e.printStackTrace();
                result = AjaxResult.error("删除失败");
            }
        } else if ("updateCount".equals(opr)) {
            // 修改购物车中商品的购买数量
            Integer id = entries.get("id", Integer.class); // 购物车id
            Integer count = entries.get("count", Integer.class); // 购物数量
            int i = cartService.update(id, count);
            if (i > 0) {
                result = AjaxResult.success("修改成功!");
            } else {
                result = AjaxResult.error("修改失败!");
            }
        } else if ("updateSelected".equals(opr)) {
            // 在购物车列表中，修改单个商品的选中状态。
            Integer id = entries.get("id", Integer.class); // 购物车id
            Boolean selected = entries.get("selected", Boolean.class); // 购物数量
            int i = cartService.updateSelected(id, selected == true ? 1 : 0);
            if (i > 0) {
                result = AjaxResult.success("修改成功!");
            } else {
                result = AjaxResult.error("修改失败!");
            }
        } else if ("updateAllSelect".equals(opr)) {
            // 在购物车列表中，修改所有商品的选中状态。
            Integer userId = entries.get("userId", Integer.class); // 登录用户的id
            Boolean selected = entries.get("selected", Boolean.class); // 购物数量
            int i = cartService.updateAllSelect(userId, selected == true ? 1 : 0);
            if (i > 0) {
                result = AjaxResult.success("修改成功!");
            } else {
                result = AjaxResult.error("修改失败!");
            }
        }else if ("getOrderPreList".equals(opr)) {
            // 查询预付订单列表(即登录用户在购物车中勾选的商品列表)
            Integer userId = entries.get("userId", Integer.class);
            List<CartItem> list = cartService.findSelectedByUserId(userId);
            List<CartItemVo> vo = new ArrayList<>();
            // 将List<CartItem> list集合的数据转换成List<CartItemVo> vo集合的数据，再响应到小程序端。
            if (list != null && list.size() > 0) {
                for (CartItem c: list) {
                    SkuItem sku = c.getSkuItem();

                    GoodsItem goods = sku.getGoods();
                    String attrsText = "";
                    // 使用for循环取出商品sku的规格属性值，多个属性值使用空格隔开。
                    for (AttrItem spec : sku.getSpecs()) {
                        for (AttrValues value : spec.getValues()) {
                            attrsText.join(" ");
                        }
                    }
                    CartItemVo cart = new CartItemVo(c.getId(), goods.getId(), sku.getId(), goods.getGoodsName(),sku.getPicture(),c.getGoodsCount(),sku.getPrice(),(int)sku.getInventory(),c.getSelected() == 1 ? true : false,attrsText);
                    cart.setNowPrice(new BigDecimal("0.9").multiply(cart.getPrice()).setScale(2));
                    vo.add(cart);
                }
            }
            result = AjaxResult.success("预付订单获取成功!", vo);
        }
        out.print(JSON.toJSONString(result));
        out.flush();
        out.close();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
